package org.vaadin.example.views.help;



import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.vaadin.flow.component.Html;
import com.vaadin.flow.component.HtmlComponent;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.accordion.Accordion;
import com.vaadin.flow.component.avatar.Avatar;
import com.vaadin.flow.component.avatar.AvatarGroup;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.checkbox.CheckboxGroup;
import com.vaadin.flow.component.checkbox.CheckboxGroupVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.icon.SvgIcon;
import com.vaadin.flow.server.StreamResource;
import com.vaadin.flow.component.combobox.MultiSelectComboBox;
import com.vaadin.flow.component.confirmdialog.ConfirmDialog;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.datetimepicker.DateTimePicker;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.html.*;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.listbox.MultiSelectListBox;
import com.vaadin.flow.component.messages.MessageInput;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.progressbar.ProgressBar;
import com.vaadin.flow.component.progressbar.ProgressBarVariant;
import com.vaadin.flow.component.radiobutton.RadioButtonGroup;
import com.vaadin.flow.component.radiobutton.RadioGroupVariant;
import com.vaadin.flow.component.tabs.TabSheet;
import com.vaadin.flow.component.textfield.*;
import com.vaadin.flow.component.timepicker.TimePicker;
import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.component.upload.receivers.MultiFileMemoryBuffer;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.Menu;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.auth.AnonymousAllowed;
import com.vaadin.flow.theme.lumo.LumoUtility;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.vaadin.example.model.Country;
import org.vaadin.example.views.MainLayout;
import org.vaadin.example.littleui.HR;
import org.vaadin.lineawesome.LineAwesomeIconUrl;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Set;



@PermitAll
@Slf4j
@PageTitle("HelpViewPage")
@Route(value = "helpView",layout = MainLayout.class)
//@PermitAll //仅允许经过身份验证的用户（具有任何角色）导航到此视图
@Menu(order = 5, icon = LineAwesomeIconUrl.FILE)
public class HelpView extends VerticalLayout {

    public HelpView() {
        Span s1 = new Span("手风琴");
        Accordion accordion = displayAccordion();

        // 创建水平分隔线
        Div hr = HR.displayHr();
        add(s1,accordion,hr);


        Span s2 = new Span("Avatar 头像");
        Avatar avatarBasic = new Avatar();
        Avatar avatarName = new Avatar("TEST");

        AvatarGroup avatarGroup = new AvatarGroup();
        for (Country country : getCountries()) {
            String name = country.getName();
            AvatarGroup.AvatarGroupItem avatar = new AvatarGroup.AvatarGroupItem(name);
            avatarGroup.add(avatar);
        }

        Avatar userAvatar = new Avatar();
        userAvatar.setImage("https://images.unsplash.com/photo-1519681393784-d120267933ba?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80");


        Div hr2 = HR.displayHr();
        add(s2,avatarBasic, avatarName,avatarGroup,userAvatar,hr2);


        Span s3 = new Span("Badge 徽章");
        Span pending = new Span("Pending");
        pending.getElement().getThemeList().add("badge");
        Span confirmed = new Span("Confirmed");
        confirmed.getElement().getThemeList().add("badge success");
        Span denied = new Span("Denied");
        denied.getElement().getThemeList().add("badge error");
        Span onHold = new Span("On hold");
        onHold.getElement().getThemeList().add("badge contrast");
        HorizontalLayout hLayout = new HorizontalLayout(pending, confirmed, denied, onHold);

        // Icon before text
        Span pending1 = new Span(createIcon(VaadinIcon.CLOCK),
                new Span("Pending"));
        pending1.getElement().getThemeList().add("badge");
// Icon after text
        Span pending2 = new Span(new Span("Pending"),
                createIcon(VaadinIcon.CLOCK));
        pending2.getElement().getThemeList().add("badge");
        HorizontalLayout h2Layout = new HorizontalLayout(pending1, pending2);

        Div hr3 = HR.displayHr();
        add(s3,hLayout,h2Layout,hr3);


        Span s4 = new Span("Button");

        Button primaryButton = new Button("Primary");
        primaryButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        Button secondaryButton = new Button("Secondary");
        Button tertiaryButton = new Button("Tertiary");
        tertiaryButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
        HorizontalLayout h3Layout = new HorizontalLayout(primaryButton, secondaryButton,tertiaryButton);

        Button primaryButton2 = new Button("Primary");
        primaryButton2.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_ERROR);
        Button secondaryButton2 = new Button("Secondary");
        secondaryButton2.addThemeVariants(ButtonVariant.LUMO_ERROR);
        Button tertiaryButton2 = new Button("Tertiary");
        tertiaryButton2.addThemeVariants(ButtonVariant.LUMO_TERTIARY, ButtonVariant.LUMO_ERROR);
        HorizontalLayout h4Layout = new HorizontalLayout(primaryButton2, secondaryButton2,tertiaryButton2);

        Button primaryButton3 = new Button("Primary");
        primaryButton3.addThemeVariants(ButtonVariant.LUMO_PRIMARY,
                ButtonVariant.LUMO_WARNING);
        Button secondaryButton3 = new Button("Secondary");
        secondaryButton3.addThemeVariants(ButtonVariant.LUMO_WARNING);
        Button tertiaryButton3 = new Button("Tertiary");
        tertiaryButton3.addThemeVariants(ButtonVariant.LUMO_TERTIARY,
                ButtonVariant.LUMO_WARNING);
        HorizontalLayout h5Layout = new HorizontalLayout(primaryButton3, secondaryButton3,tertiaryButton3);

        Button largeButton = new Button("Large");
        largeButton.addThemeVariants(ButtonVariant.LUMO_LARGE);
        Button normalButton = new Button("Normal");
        Button smallButton = new Button("Small");
        smallButton.addThemeVariants(ButtonVariant.LUMO_SMALL);
        HorizontalLayout h6Layout = new HorizontalLayout(largeButton, normalButton,smallButton);

        Div hr4 = HR.displayHr();
        add(s4,h3Layout,h4Layout,h5Layout,h6Layout,hr4);

        Span s5 = new Span("CheckboxGroup-demo");
        CheckboxGroup<String> checkboxGroup = new CheckboxGroup<>();
        checkboxGroup.setLabel("Export data");
        checkboxGroup.setItems("Order ID", "Product name", "Customer",
                "Status");
        checkboxGroup.select("Order ID", "Customer");
        checkboxGroup.addThemeVariants(CheckboxGroupVariant.LUMO_VERTICAL);
        // 添加值改变事件监听器
        checkboxGroup.addValueChangeListener(event -> {
            // 处理选择的值
            Set<String> selectedValues = event.getValue();
            // 这里可以添加逻辑，比如更新 UI 或处理数据
            log.info("选中的checkbox:{}",selectedValues.toString());
        });
        Div hr5 = HR.displayHr();
        add(s5,checkboxGroup,hr5);


        Span s6 = new Span("ComboBox");
        ComboBox<Country> countryComboBox = new ComboBox<>("Select Country");
        countryComboBox.setItems(getCountries()); // 设置 ComboBox 的项
        countryComboBox.setItemLabelGenerator(Country::getName); // 用于前端显示的标签
        // 监听选项变化
        countryComboBox.addValueChangeListener(event -> {
            Country selectedCountry = event.getValue();
            if (selectedCountry != null) {
                Long selectedId = selectedCountry.getId(); // 获取 ID
                // 在这里可以处理 ID，如存储到数据库等
                log.info("Selected country id: {}", selectedId);
                Notification.show("选中了"+selectedCountry.getName());
            }
        });
        Div hr6 = HR.displayHr();
        add(s6,countryComboBox,hr6);


        Span s7 = new Span("ConfirmDialog");
        //demo1 删除确认
        Button deleteButton = new Button("删除项");
        // 添加按钮点击事件
        deleteButton.addClickListener(event -> {
            // 创建确认对话框
            ConfirmDialog dialog = new ConfirmDialog();
            dialog.setHeader("确认");
            dialog.setText("您确定要删除该项吗？");

            // 设置确认按钮的事件
            dialog.setCancelable(true);
            dialog.setConfirmText("确认");
            dialog.setConfirmButtonTheme("error primary");
            dialog.setCancelText("取消");
            dialog.addConfirmListener(confirmEvent -> {
                // 处理确认事件
                log.info("确认删除");
                Notification.show("项已删除!");

            });
            dialog.addCancelListener(cancelEvent -> {
                // 处理取消事件
                log.info("操作已取消");
                Notification.show("操作已取消!");

            });

            // 显示对话框
            dialog.open();
        });

        //demo2 使用建议
        Button recommendButton = new Button("提示");
        recommendButton.addClickListener(event -> {
            ConfirmDialog dialog = new ConfirmDialog();
            dialog.setHeader("导出失败");
            dialog.setText(new Html(
                    "<p>导出报告Q4时出错。请重试，如果问题仍然存在，请联系 <a href=\"mailto:support@company.com\">support@company.com</a></p>"));
            dialog.setConfirmText("我知道了");
            dialog.addConfirmListener(confirmEvent -> {
                // 处理确认事件
                log.info("我知道了");
                Notification.show("我知道了!");
            });
            // 显示对话框
            dialog.open();
        });

        //demo3 拒绝按钮
        Button rejectButton = new Button("拒绝保存");
        rejectButton.addClickListener(event -> {
            ConfirmDialog dialog = new ConfirmDialog();
            dialog.setHeader("未保存的更改");
            dialog.setText(
                    "您想在导航离开之前放弃或保存更改吗");

            dialog.setCancelable(true);
            dialog.setCancelText("取消");
            dialog.addCancelListener(cancelEvent -> {
                // 处理取消事件
                log.info("操作已取消");
                Notification.show("操作已取消!");
            });
            dialog.setRejectable(true);
            dialog.setRejectText("丢弃变更");
            dialog.setConfirmText("保存变更");
            // 显示对话框
            dialog.open();
        });
        Div hr7 = HR.displayHr();
        add(s7,deleteButton,recommendButton,rejectButton,hr7);


        Span s8 = new Span("DatePicker");
        DatePicker datePicker = new DatePicker("选择日期");
        datePicker.setLabel("选择一个日期");
        // 设置日期格式
        datePicker.setI18n(new DatePicker.DatePickerI18n().setCancel("取消")
                .setToday("今天")
                .setMonthNames(List.of("一月", "二月", "三月", "四月", "五月", "六月",
                        "七月", "八月", "九月", "十月", "十一月", "十二月")));
        // 添加监听器以捕获日期选择事件
        datePicker.addValueChangeListener(event -> {
            // 获取选择的日期
            LocalDate date = event.getValue();
            log.info("选择的日期:{}",date.toString());
        });
        Div hr8 = HR.displayHr();
        add(s8,datePicker,hr8);


        Span s9 = new Span("DateTimePicker");
        DateTimePicker dateTimePicker = new DateTimePicker("选择日期和时间");
        // 可以设置默认值
        dateTimePicker.setValue(LocalDateTime.now());
        // 你可以为选择事件添加监听器
        dateTimePicker.addValueChangeListener(event -> {
            LocalDateTime selectedDateTime = event.getValue();
            System.out.println("选择的日期时间: " + selectedDateTime);
        });
        Div hr9 = HR.displayHr();
        add(s9,dateTimePicker,hr9);

        Span s010 = new Span("TimePicker");
        TimePicker timePicker = new TimePicker();
        timePicker.setLabel("Meeting time");
        timePicker.setStep(Duration.ofMinutes(30));
        timePicker.setValue(LocalTime.of(12, 30));
        Div hr010 = HR.displayHr();
        add(s010,timePicker,hr010);


        Span s10 = new Span("Dialog");
        Button showDialogButton = new Button("new弹窗");
        showDialogButton.addClickListener(event -> {
            Dialog dialog = new Dialog();
            dialog.setWidth("368px");
            dialog.setHeaderTitle("New employee");
            TextField tf1 = new TextField("First Name");
            tf1.setWidth("276px");
            TextField tf2 = new TextField("Last Name");
            tf2.setWidth("276px");
            VerticalLayout layout = new VerticalLayout();
            layout.add(tf1,tf2);
            dialog.add(layout);
            Button saveButton = new Button("Save",e->{

                String value = tf1.getValue();
                if (StringUtils.isEmpty(value)) {
                    Notification.show("First Name 不能为空!");
                }else {
                    s10.setText(value);
                    // 关闭对话框
                    dialog.close();
                }

            });
            saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
            Button cancelButton = new Button("Cancel", e -> dialog.close());
            dialog.getFooter().add(cancelButton);
            dialog.getFooter().add(saveButton);
            // 显示对话框
            dialog.open();
        });

        Button openDialogButton = new Button("view弹窗", event -> openDialog());

        Div hr10 = HR.displayHr();
        add(s10,showDialogButton,openDialogButton,hr10);



        Span s11 = new Span("各种输入窗");
        EmailField validEmailField = new EmailField();
        validEmailField.setLabel("Email address");
        validEmailField.getElement().setAttribute("name", "email");
        validEmailField.setValue("julia@email.com");
        validEmailField.setErrorMessage("Enter a valid email address");
        validEmailField.setPrefixComponent(VaadinIcon.ENVELOPE.create());
        validEmailField.setClearButtonVisible(true);

        NumberField dollarField = new NumberField();
        dollarField.setLabel("Balance");
        dollarField.setValue(200.0);
        Div dollarPrefix = new Div();
        dollarPrefix.setText("$");
        dollarField.setPrefixComponent(dollarPrefix);
        dollarField.setClearButtonVisible(true);

        IntegerField integerField = new IntegerField();
        integerField.setLabel("Quantity");
        integerField.setHelperText("Max 10 items");
        integerField.setRequiredIndicatorVisible(true);
        integerField.setMin(1);
        integerField.setMax(10);
        integerField.setValue(2);
        integerField.setStepButtonsVisible(true);

        integerField.setI18n(new IntegerField.IntegerFieldI18n()
                .setRequiredErrorMessage("Field is required")
                .setBadInputErrorMessage("Invalid number format")
                .setMinErrorMessage("Quantity must be at least 1")
                .setMaxErrorMessage("Maximum 10 items available"));

        BigDecimalField bigDecimalField = new BigDecimalField();
        bigDecimalField.setLabel("Result");
        bigDecimalField.setWidth("240px");
        bigDecimalField.setValue(new BigDecimal("948205817.472950487"));


        IntegerField xField = new IntegerField();
        xField.setLabel("X");
        xField.setValue(-1284);


        NumberField numberField = new NumberField();
        numberField.setLabel("Duration (hours)");
        numberField.setStep(0.5);
        numberField.setValue(12.5);
        numberField.setStepButtonsVisible(true);
        numberField.setI18n(new NumberField.NumberFieldI18n()
                .setBadInputErrorMessage("Invalid number format")
                .setStepErrorMessage("Duration must be a multiple of 0.5"));

        PasswordField passwordField1 = new PasswordField();
        passwordField1.setLabel("Password");
        passwordField1.setValue("Ex@mplePassw0rd");
        passwordField1.setClearButtonVisible(true);
        passwordField1.setPrefixComponent(VaadinIcon.LOCK.create());


        HorizontalLayout layout = new HorizontalLayout();
//        layout.setPadding(true);
        layout.add(validEmailField);
        layout.add(dollarField);
        layout.add(integerField);
        layout.add(bigDecimalField);
        layout.add(xField);
        layout.add(numberField);
        layout.add(passwordField1);


        PasswordField passwordField = new PasswordField();
        passwordField.setLabel("Password2");

        Icon checkIcon = VaadinIcon.CHECK.create();
        checkIcon.setVisible(false);
        checkIcon.getStyle().set("color", "var(--lumo-success-color)");
        passwordField.setSuffixComponent(checkIcon);

        Div passwordStrength = new Div();
        Span passwordStrengthText = new Span("week");
        passwordStrengthText.setClassName("password-strength-week");
        passwordStrength.add(new Text("Password strength: "),
                passwordStrengthText);
        passwordField.setHelperComponent(passwordStrength);
        passwordField.setClearButtonVisible(false);


        passwordField.setValueChangeMode(ValueChangeMode.EAGER); //设置实时监听
        passwordField.addValueChangeListener(event -> {
            String value = event.getValue();
            log.info("ValueChangeListener value: {}" , value);

            if (value.length() <= 3) {
                checkIcon.setVisible(false);
                passwordStrengthText.setText("week");
                passwordStrengthText.setClassName("password-strength-week");
            }
            if (value.length() >3 && value.length() <= 6) {
                checkIcon.setVisible(false);
                passwordStrengthText.setText("moderate");
                passwordStrengthText.setClassName("password-strength-moderate");
            }
            if (value.length() >6 && value.length() <= 9) {
                passwordStrengthText.setText("strong");
                passwordStrengthText.setClassName("password-strength-strong");
                checkIcon.setVisible(true);
            }
        });

        TextField textField = new TextField();
        textField.setLabel("Street Address");
        textField.setValue("Ruukinkatu 2");
        textField.setClearButtonVisible(true);
        textField.setPrefixComponent(VaadinIcon.MAP_MARKER.create());


        TextField phoneField = new TextField("Phone number");
        phoneField.setRequiredIndicatorVisible(true);
        phoneField.setPattern(
                "^[+]?[\\(]?[0-9]{3}[\\)]?[\\-]?[0-9]{3}[\\-]?[0-9]{4,6}$");
        phoneField.setAllowedCharPattern("[0-9()+-]");
        phoneField.setMinLength(5);
        phoneField.setMaxLength(18);
        phoneField.setHelperText("Format: +(123)456-7890");
        phoneField.setI18n(new TextField.TextFieldI18n()
                .setRequiredErrorMessage("Field is required")
                .setMinLengthErrorMessage("Minimum length is 5 characters")
                .setMaxLengthErrorMessage("Maximum length is 18 characters")
                .setPatternErrorMessage("Invalid phone number format"));


        TextArea textArea = new TextArea();
        textArea.setLabel("Comment");
        textArea.setMaxLength(150);
        textArea.setValueChangeMode(ValueChangeMode.EAGER);
        textArea.addValueChangeListener(e -> {
            e.getSource()
                    .setHelperText(e.getValue().length() + "/" + 150);
        });
        textArea.setValue("Great job. This is excellent!");


        TextField findField = new TextField();
        findField.setPlaceholder("Search");
        findField.setPrefixComponent(new Icon("lumo", "search"));
        findField.setTooltipText("Wrap in “quotes” for exact phrase");

        Div hr11 = HR.displayHr();
        add(s11,layout,passwordField,textField,phoneField,textArea,findField,hr11);


        TabSheet tabSheet = new TabSheet();
        tabSheet.add("Dashboard",
                new Div(new Text("This is the Dashboard tab content")));
        tabSheet.add("Payment",
                new Div(new Text("This is the Payment tab content")));
        tabSheet.add("Shipping",
                new Div(new Text("This is the Shipping tab content")));
        Div hr12 = HR.displayHr();
        add(tabSheet,hr12);


        RadioButtonGroup<String> radioGroup = new RadioButtonGroup<>();
        radioGroup.addThemeVariants(RadioGroupVariant.LUMO_VERTICAL);
        radioGroup.setLabel("Travel class");
        radioGroup.setItems("Economy", "Business", "First Class");
        radioGroup.addValueChangeListener(event -> {
            String value = event.getValue();
            log.info("RadioButtonGroup ValueChangeListener value: {}" , value);
        });
        Div hr13 = HR.displayHr();
        add(radioGroup,hr13);

        ProgressBar progressBar = new ProgressBar();
        progressBar.setValue(0.5);

        ProgressBar progressBar2 = new ProgressBar();
        progressBar2.setIndeterminate(true);

        // Contrast
        ProgressBar progressBarContrast = new ProgressBar();
        progressBarContrast.addThemeVariants(ProgressBarVariant.LUMO_CONTRAST);
        progressBarContrast.setValue(0.5);

// Success
        ProgressBar progressBarSuccess = new ProgressBar();
        progressBarSuccess.addThemeVariants(ProgressBarVariant.LUMO_SUCCESS);
        progressBarSuccess.setValue(0.75);

// Error
        ProgressBar progressBarError = new ProgressBar();
        progressBarError.addThemeVariants(ProgressBarVariant.LUMO_ERROR);
        progressBarError.setValue(0.2);

        Div hr14 = HR.displayHr();
        add(progressBar,progressBar2,progressBarContrast,progressBarSuccess,progressBarError,hr14);


        ProgressBar progressBarExport = new ProgressBar();
        progressBarExport.setIndeterminate(true);
        // Associates the labels with the bar programmatically, for screen
// readers:
        progressBarExport.getElement().setAttribute("aria-labelledby", "pblbl");
        progressBarExport.getElement().setAttribute("aria-describedby", "sublbl");

        NativeLabel progressBarLabel = new NativeLabel("Generating report...");
        progressBarLabel.setId("pblbl");
        progressBarLabel.addClassName(LumoUtility.TextColor.SECONDARY);

        Span progressBarSubLabel = new Span("Process can take upwards of 10 minutes");
        progressBarSubLabel.setId("sublbl");
        progressBarSubLabel.addClassNames(LumoUtility.TextColor.SECONDARY, LumoUtility.FontSize.XSMALL);

        Div hr15 = HR.displayHr();
        add(progressBarLabel, progressBarExport, progressBarSubLabel,hr15);


        Span s16 = new Span("MultiSelectComboBox demo");
        MultiSelectComboBox<Country> comboBox = new MultiSelectComboBox<>(
                "Countries");
        comboBox.setItems(getCountries());
        comboBox.setItemLabelGenerator(Country::getName);
        comboBox.addValueChangeListener(event -> {
            Set<Country> countrySet =  event.getValue();
            log.info("countrySet: {}", countrySet);
        });
        Div hr16 = HR.displayHr();
        add(s16,comboBox,hr16);

        MessageInput input = new MessageInput();
        input.addSubmitListener(submitEvent -> {
            Notification.show("Message received: " + submitEvent.getValue(),
                    3000, Notification.Position.MIDDLE);
        });
        Div hr17 = HR.displayHr();
        add(input,hr17);


        Span s18 = new Span("Notification demo");
        Button toast1 = new Button("toast1", event -> {
            // When creating a notification using the `show` static method,
// the duration is 5-sec by default.
            Notification.show("Financial report generated");
        });

        Button toast2 = new Button("toast2", event -> {
            Notification notification = Notification.show("Application submitted!");
            notification.addThemeVariants(NotificationVariant.LUMO_SUCCESS);
        });

        Button toast3 = new Button("toast3",evt -> {
            Notification notification = new Notification();
            notification.addThemeVariants(NotificationVariant.LUMO_WARNING);
            Div text = new Div(new Text(
                    "Your session will expire in 5 minutes due to inactivity."),
                    new HtmlComponent("br"),
                    new Text("Close this warning to continue working."));
            Button closeButton = new Button(new Icon("lumo", "cross"));
            closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);
            closeButton.setAriaLabel("Close");
            closeButton.addClickListener(event -> {
                notification.close();
            });
            HorizontalLayout layoutH = new HorizontalLayout(text, closeButton);
            layoutH.setAlignItems(Alignment.CENTER);
            notification.add(layoutH);
            notification.open();
        });

        Button toast4 = new Button("toast4",evt -> {
            Notification notification = new Notification();
            notification.addThemeVariants(NotificationVariant.LUMO_ERROR);
            Div text = new Div(new Text("Failed to generate report"));
            Button closeButton = new Button(new Icon("lumo", "cross"));
            closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY_INLINE);
            closeButton.setAriaLabel("Close");
            closeButton.addClickListener(event -> {
                notification.close();
            });
            HorizontalLayout layoutH = new HorizontalLayout(text, closeButton);
            layoutH.setAlignItems(Alignment.CENTER);
            notification.add(layoutH);
            notification.open();
        });
        Div hr18 = HR.displayHr();
        add(s18,toast1,toast2,toast3,toast4,hr18);

        //列表框允许用户从可滚动的项目列表中选择一个或多个值
        Span s19 = new Span("MultiSelectListBox demo");
        MultiSelectListBox<Country> listBox = new MultiSelectListBox<>();
        listBox.setItems(getCountries());
        listBox.select(getCountries().get(0), getCountries().get(3));
        listBox.setHeight("200px");
        listBox.setClassName("lstbox");
        listBox.setTooltipText("this is a listbox");


        // 设置展示给用户的名称
        listBox.setItemLabelGenerator(Country::getName);

        // 添加一个值改变监听器
        listBox.addValueChangeListener(event -> {
            String selectedCountries = event.getValue().stream()
                    .map(Country::getName)
                    .reduce((a, b) -> a + ", " + b)
                    .orElse("No countries selected");
            Notification.show(selectedCountries);
        });

        Div hr19 = HR.displayHr();
        add(s19,listBox,hr19);


        Div card = new Div();
        card.setClassName("card");
        card.getElement().getStyle().set("border", "1px solid #ccc");
        card.getElement().getStyle().set("border-radius", "5px");
        card.getElement().getStyle().set("padding", "16px");
        card.getElement().getStyle().set("width", "300px");
        card.getElement().getStyle().set("box-shadow", "0 4px 8px rgba(0,0,0,0.1)");

        // 添加标题
        H3 title = new H3("Card Title");
        card.add(title);

        // 添加图片
//        Image image = new Image("https://via.placeholder.com/300", "Placeholder image");
        Image image = new Image("https://images.unsplash.com/photo-1512273222628-4daea6e55abb?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80", "Placeholder image");
        image.setWidth("300px");
        card.add(image);
        // 添加按钮
        Button button = new Button("Click me");
        card.add(button);
        Div hrDiv = HR.displayHr();
        add(card,hrDiv);


        Span fSpan = new Span("FormLayout demo");
        TextField firstName = new TextField("First name");
        TextField lastName = new TextField("Last name");
        TextField username = new TextField("Username");
        PasswordField password = new PasswordField("Password");
        PasswordField confirmPassword = new PasswordField("Confirm password");
        FormLayout formLayout = new FormLayout();
        formLayout.add(firstName, lastName, username, password, confirmPassword);
        formLayout.setResponsiveSteps(
                // Use one column by default
                new FormLayout.ResponsiveStep("0", 1),
                // Use two columns, if layout's width exceeds 500px
                new FormLayout.ResponsiveStep("500px", 2));
// Stretch the username field over 2 columns
        formLayout.setColspan(username, 2);
        Div fhr = HR.displayHr();
        add(fSpan,formLayout,fhr);


        Span sSpan = new Span("Upload demo");
        MultiFileMemoryBuffer buffer = new MultiFileMemoryBuffer();
        Upload upload = new Upload(buffer);
        //限制上传文件格式
        //  upload.setAcceptedFileTypes("application/pdf", ".pdf");
        //默认情况下，“上传”不限制可以上传的文件数量。但是，您可以设置文件计数限制
        upload.setMaxFiles(3);
        //设置最大字节数来限制文件大小。但默认情况下，没有限制
        // 10MB
        int maxFileSizeInBytes = 10 * 1024 * 1024;
        upload.setMaxFileSize(maxFileSizeInBytes);
        upload.addSucceededListener(event -> {
            String fileName = event.getFileName();
            log.info("fileName:{}", fileName);
            String mainName = FileNameUtil.mainName(fileName);
            log.info("file mainName:{}", mainName);
            String extName = FileNameUtil.extName(fileName);
            log.info("file extName:{}", extName);
            InputStream in = buffer.getInputStream(fileName);
            // Do something with the file data
            // processFile(inputStream, fileName);
            BufferedOutputStream out = FileUtil.getOutputStream("/Users/liuzh/Documents/"+fileName);
            long copySize = IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE);
            System.err.println(copySize);
            IoUtil.closeIfPosible(in);
            IoUtil.closeIfPosible(out);
        });
        upload.addFileRejectedListener(event -> {
            String errorMessage = event.getErrorMessage();
            Notification notification = Notification.show(errorMessage, 5000,
                    Notification.Position.MIDDLE);
            notification.addThemeVariants(NotificationVariant.LUMO_ERROR);
        });

        Div fhr2 = HR.displayHr();
        add(sSpan,upload,fhr2);

//        Image imageTest = new Image("images/empty-plant.png", "My Alt Image");
        Image imageTest = new Image("https://images.unsplash.com/photo-1519681393784-d120267933ba?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80", "My Alt Image");


        SvgIcon svgIcon = new SvgIcon();
        svgIcon.setSrc("icons/hellokitty_1.svg");
        SvgIcon svgIcon2 = new SvgIcon();
        svgIcon2.setSrc("icons/hellokitty.svg");

        SvgIcon svgIcon3 = new SvgIcon();
        svgIcon3.setSrc("icons/hello.svg");


        Div hr318 = HR.displayHr();
        add(imageTest,svgIcon,svgIcon2,svgIcon3,hr318);



    }




    private void openDialog() {
        Dialog dialog = new Dialog();
        dialog.setWidth("388px"); // 设置弹窗宽度

        // 创建输入框
        TextField nameField = new TextField("Name", "Enter your name");
        nameField.setWidth("300px");
        nameField.setValue("test");
        nameField.setReadOnly(true);
        TextField emailField = new TextField("Email", "Enter your email");
        emailField.setWidth("300px");
        emailField.setValue("efdxuwef@163.com");
        emailField.setReadOnly(true);

        TextField addressField = new TextField("Address", "Enter your address");
        addressField.setWidth("300px");
        addressField.setValue("4188 Crystal Orchard, Mousie, USA");
        addressField.setReadOnly(true);



        VerticalLayout layout = new VerticalLayout();
        layout.add(nameField);
        layout.add(emailField);
        layout.add(addressField);

        // 添加输入框到对话框
        dialog.add(layout);

        dialog.setHeaderTitle("User details");

        Button closeButton = new Button(new Icon("lumo", "cross"),
                (e) -> dialog.close());
        closeButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
        dialog.getHeader().add(closeButton);


        dialog.open();
    }


    private List<Country> getCountries() {
        // 这里是一个示例，实际中应该从数据库或其他地方获取数据
        return List.of(
                new Country(1L, "China"),
                new Country(2L, "United States"),
                new Country(3L, "Germany"),
                new Country(4L, "Japan"),
                new Country(5L, "India"),
                new Country(6L, "Kndia"),
                new Country(7L, "Dndia"),
                new Country(8L, "Mndia"),
                new Country(9L, "Bndia"),
                new Country(10L, "Cndia"),
                new Country(11L, "Xndia")
        );
    }



    private Accordion displayAccordion(){
        Accordion accordion = new Accordion();

        Span name = new Span("Sophia Williams");
        Span email = new Span("sophia.williams@company.com");
        Span phone = new Span("(501) 555-9128");
        VerticalLayout accordionItemLayout = new VerticalLayout(name,
                email, phone);
        accordionItemLayout.setSpacing(false);
        accordionItemLayout.setPadding(false);
        accordion.add("Personal information", accordionItemLayout);

        Span name2 = new Span("4027 Amber Lake Canyon");
        Span email2 = new Span("72333-5884 Cozy Nook");
        Span phone2 = new Span("Arkansas");
        VerticalLayout accordionItemLayout2 = new VerticalLayout(name2, email2, phone2);
        accordionItemLayout2.setSpacing(false);
        accordionItemLayout2.setPadding(false);
        accordion.add("Billing Address", accordionItemLayout2);


        return accordion;
    }

    private Icon createIcon(VaadinIcon vaadinIcon) {
        Icon icon = vaadinIcon.create();
        icon.getStyle().set("padding", "var(--lumo-space-xs)");
        return icon;
    }


}
